import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

import { resetRouter } from '@/router/index.js'
const state = {
  token: getToken() || null,
  userInfo: {}
}

// 修改状态
const mutations = {
  // 设置token
  setToken(state, token) {
    state.token = token // 设置token

    setToken(token)
  },
  // 删除token
  removeToken(state) {
    state.token = null // 删除vuex的token
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 删除用户信息
  reomveUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async userLogin(ctx, data) {
    const res = await login(data)
    ctx.commit('setToken', res)
    return res
  },

  logout(context, data) {
    // const res = await login(data)
    context.commit('removeToken')
    // 清除用户信息
    context.commit('reomveUserInfo')

    resetRouter()

    // 调用另一个模块中的mutatioin
    context.commit('menu/setMenuList', [], { root: true })
  },
  // 获取用户资料action
  async getUserInfo(context) {
    const result = await getUserInfo()
    // 为了获取头像
    const baseInfo = await getUserDetailById(result.userId)
    // 合并验证结果
    context.commit('setUserInfo', { ...result, ...baseInfo })
    // context.commit('setUserInfo', result)
    return result.roles
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations
}

